/**
 * Copyright (C) 2002-2006 WUZEWEN. All rights reserved.
 * WUZEWEN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package com.kingcore.director.reminder.ui;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Observable;
import java.util.ResourceBundle;
import java.util.concurrent.TimeUnit;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.text.StyledEditorKit;

import org.apache.log4j.Logger;

import wzw.beans.DbBean;
import wzw.swing.PlainTextPane;
import wzw.swing.event.LanguageChangeListener;
import wzw.util.ComponentUtil;
import wzw.util.I18nUtil;
import wzw.util.I18nUtils;

import com.kingcore.director.DirectorConstants;
import com.kingcore.director.DirectorContext;
import com.kingcore.director.base.ui.DirectorDialog;
import com.kingcore.director.core.util.AdUtil;
import com.kingcore.director.core.util.DirectorComponentUtils;
import com.kingcore.director.core.util.DirectorFileUtils;
import com.kingcore.director.core.util.DirectorStringUtils;
import com.kingcore.director.core.util.Formatter;
import com.kingcore.director.main.Main;
import com.kingcore.director.reminder.bean.AwokeBean;
import com.kingcore.director.reminder.clock.Timer;
import com.kingcore.director.reminder.clock.TimerTask;
import com.kingcore.framework.context.ApplicationContext;



/**
 * <p>通用消息窗口</p>
 * @author	WUZEWEN on 200591-29
 * @version	1.0
 * @see		Object#equals(java.lang.Object)
 * @see		Object#hashCode()
 * @see		HashMap
 * @since	JDK5
 */

public class AwokeMessageDialog extends DirectorDialog 
	             implements WindowListener,LanguageChangeListener, ItemListener{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public static int width = 325;
	public static int height = 205; 
	
	public static final String appIco = "./resource/director.gif";
	private static Logger log=Logger.getLogger(AwokeMessageDialog.class);
	private AwokeBean awokeBean=null;
	private Timer timer;
	TimerTask currentTimerTask; 

	private JScrollPane scrollPane = null;
	private JTextArea content = null;
	private JTextPane contentPane = null;
	private JLabel infor_time = null;
	private JLabel awokeTimeLabel = null;
	private JButton confirmButton = null;
	private JTextField timeNum = null;
	private Window parent=null;
	private JRadioButton jRadioButton_1 = null;
	private JRadioButton jRadioButton_2 = null;
	ButtonGroup bg = new ButtonGroup();
	private JComboBox jComboBox = null;
	private JLabel jLabel3 = null;
	private JLabel lbl_awokeTime = null;

	
	private JPanel jContentPane = null;
	private JPanel mainPanel;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}


	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initializeInterface() {
		//this.setIconImage(Toolkit.getDefaultToolkit().createImage(appIco));

	    this.setAlwaysOnTop(true);
		this.setSize(width, height);
		this.setTitle( "提醒--"+awokeBean.getTitle() );
		this.setContentPane(getJContentPane());
		String content = awokeBean.getContent();
		if (content!=null && content.trim().length()>0) {
			String contentType = "text/plain";
			
			//System.out.println(content);
//			if (DirectorStringUtils.needAddAnchorHtmlCode(content)) {
//				content = DirectorStringUtils.addAnchorHtmlCode(content);
//			}
			content = DirectorStringUtils.addAnchorHtmlCode(content);
			log.debug(content);
			
			if (DirectorStringUtils.isContainsHtmlCode(content)) {
				contentType = "text/html";
			}
			StyledEditorKit kit = new StyledEditorKit();
			this.getContentTextPane().setEditorKitForContentType(contentType,kit);  //Must be StyledEditorKit
			//this.getContentTextPane().setContentType(contentType); //加这句导致jdk1.6下html显示有问题。
		}
		this.getContentTextPane().setText( content==null?"":content );

		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		this.lbl_awokeTime.setText( "开始于:"+ sdf.format( awokeBean.getThisBeginTime() ));
		this.lbl_awokeTime.setText( "开始于:"+ awokeBean.getBeginTime() ); 
		this.setResizable(false);
		//设置监听器
		// this.addWindowListener( this );   //去掉，否则出现两个或以上的窗口为争取顶层打架现象。
		
		//更新语言
		this.update(null,null);
	}

	private JTextArea getContent() {
		if (content == null) {
			content = new JTextArea();
			content.setEditable(false);
			content.setEditable(false);	
			content.setBackground(new Color(239,239,239));
		}
		return content;
	}
	private JTextPane getContentTextPane() {
		//System.out.println("-----------12");
		if (contentPane == null) {
			contentPane = new PlainTextPane();
			contentPane.setEditable(false);
			//contentPane.setBackground(new Color(146,151,161,0)); //214,217,223,0
			//contentPane.set
			contentPane.setContentType("text/html");   // this is the key line.
			
			//getJContentPane().setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
			//setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));  //ok
			//contentPane.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));//fail and useless
			
			contentPane.addHyperlinkListener(new HyperlinkListener() { 
		        public void hyperlinkUpdate(HyperlinkEvent e) {
					//System.out.println("-----------2");
		        	HyperlinkEvent.EventType type = e.getEventType();
		            if (type == HyperlinkEvent.EventType.ENTERED) {
		                //System.out.println("11"+e.getURL().toString());
		                //infor.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); //fail
		                //contentPane.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); //fail
		                setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); //ok,and it is different with this.setCursor(...)
		                	
		            } else if (type == HyperlinkEvent.EventType.EXITED) {
		            	//System.out.println("Exited");
		                setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
		                
		            } else if (type == HyperlinkEvent.EventType.ACTIVATED) {
//		                HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent) e;
//		                HTMLDocument doc = (HTMLDocument) contentPane.getDocument();
//		                doc.processHTMLFrameHyperlinkEvent(evt);
//		                pane.setPage(he.getURL());
						//System.out.println("-----------32");
		        		try {
		        			String url=e.getURL().toString();
		        			if (url==null) {
								return ;
							}
		        			url = url.trim();
		        			DirectorFileUtils.openFile(url);
		        		} catch (Exception ex) {
		        			ex.printStackTrace();
		        		}
		        		
		            }
		        }
		      });		    
		}
		return contentPane;
	}
	
	/**
	 * <p>
	 *   上下布局风格： 
	 *     > button, text等高度统一为20px;
	 *     > 对象之间、对象与容器之间的上下间隔统一为 1px;
	 *   左右布局风格：
	 *     > 对象宽度视情况而定;
	 *     > 对象之间、对象与容器之间的上下间隔至少为 1px;
	 *     
	 * </p>
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(null);

			scrollPane = new JScrollPane(getContentTextPane());
			scrollPane.setBounds(new java.awt.Rectangle(1,1,318,99));
			//scrollPane.setViewportView(getContentTextPane());
			scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);  
	        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); 

			lbl_awokeTime = new JLabel();
			lbl_awokeTime.setBounds(new java.awt.Rectangle(1,101,162,20));
			lbl_awokeTime.setText("2005-05");

			jContentPane.add(getTimeEnableCheckBox(), null);		
			jContentPane.add(getTime(), null);		
			infor_time = new JLabel();
			infor_time.setBounds(new java.awt.Rectangle(208,101,200,20));
			infor_time.setText("秒后自动关闭窗口");
			
				
			jContentPane.add(getJRadioButton_1(), null);
			jContentPane.add(getJComboBox(), null);	
			jLabel3 = new JLabel();
			jLabel3.setBounds(new java.awt.Rectangle(220,122,172,20));
			jLabel3.setText("后再提醒");

			jContentPane.add(getJRadioButton_2(), null);
			jContentPane.add(getAdLink(), null);
			
			jContentPane.setLayout(null);
			jContentPane.setSize(width, 208);
			jContentPane.add(scrollPane, null);
			jContentPane.add(infor_time, null);		
			jContentPane.add(getConfirmButton(), null);
			//jContentPane.add(getAwokeTimeLabel(), null);

		    bg.add(jRadioButton_1);
		    bg.add(jRadioButton_2);
		    
		    jContentPane.add(jLabel3, null);
		    jContentPane.add(lbl_awokeTime, null);

		    if( this.getAwokeBean().getNeedAffirm().toUpperCase().equals("Y")){
				this.getJRadioButton_1().setSelected(true);
			}else{
				this.getJRadioButton_2().setSelected(true);
			}
		}
		return jContentPane;
	}

	private JEditorPane adPane = null;
	private JEditorPane getAdLink() {
		if (adPane==null) {
			adPane = new JEditorPane( );
			adPane.setEditable(false);
			adPane.setBackground(new Color(238,238,238,0));
			adPane.setContentType("text/html");
			adPane.setBounds(new java.awt.Rectangle(80,149,138,21));
			adPane.setOpaque(false);
			adPane.addHyperlinkListener(new HyperlinkListener() {
			      public void hyperlinkUpdate(HyperlinkEvent e) {
			          if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
			            try {
//			              String command = "explorer.exe "//如果是记事本打开,可用 notepad.exe
//			                  + e.getURL().toString();
//			              Runtime.getRuntime().exec(command);
			              DirectorComponentUtils.openWebUrl( e.getURL().toString() );

			            }
			            catch (Exception ex) {
			              ex.printStackTrace();
			            }
			          }
			        }
			      });
		}
		return adPane;
	}

	/**
	 * override parent method.
	 * 
	 * @author WZWEN on 2006-04-28
	 */
    protected void processWindowEvent(WindowEvent e) {
        if (e.getID() == WindowEvent.WINDOW_CLOSING
        		&& !DirectorContext.isAwokeCloseEnabled() ) {
        	
//	        int state = this.getExtendedState();	 
//	        
//	        // Clear the maximized bits
//	        state &= ~Frame.MAXIMIZED_BOTH;
//	    
//	        // Minimize the frame	
//	        this.setExtendedState(ICONIFIED);
			
			//executeExitSystem();	        
            return;
        }
        super.processWindowEvent(e);
    }

	private void closeWindow(){
		log.debug("closeWindow----" );
		if ( DirectorConstants.AwokeStyle_MsnTips.equals(awokeStyle)) {
			//System.out.println("closeWindow----" + current_PopupWindow_Num);
			Current_PopupWindow_Numbers.remove((Object)current_PopupWindow_Num);
		}else{
			current_NormalWindow_Num --;
		}
		
		log.debug("close Bean.....");
		AwokeBean awokeBean=this.getAwokeBean();
		if(this.jRadioButton_1.isSelected()){  // 过会儿提醒，不处理数据库
			long interval=1000*60*30;
			String value= ComponentUtil.getSelectedItemCode(jComboBox);
			log.debug("again at "+value);
			if(value.equals("1m")){
				interval=1000*60;
			}else if(value.equals("5m")){
				interval=1000*60*5;
			}else if(value.equals("10m")){
				interval=1000*60*10;				
			}else if(value.equals("30m")){
				interval=1000*60*30;					
			}else if(value.equals("1h")){
				interval=1000*60*60;						
			}else if(value.equals("2h")){
				interval=1000*60*60*2;						
			}else if(value.equals("5h")){
				interval=1000*60*60*5;						
			}else if(value.equals("1d")){
				interval=1000*60*60*24;						
			}
			log.info("create new awokeBean.");
			
			this.getTimer().schedule(
					new TimerTask(awokeBean,
							this.getTimer()){
						public void run(){
							AwokeBean awbean=(AwokeBean)this.paramObject;
							log.info("Exec:"+awbean.getTitle());
							AwokeMessageDialog mw1=new AwokeMessageDialog(awbean,this.getTimer());
							//mw1.getCursor();
							mw1.setVisible(true);    

							//ComponentUtil.setLocationToCenter(mw1);
//							mw1.setVisible(true);
//							mw1.toFront();
//							mw1.setSize(MessageWindowDialog.width, MessageWindowDialog.height);
//							mw1.setModal(true);
//							mw1.setAlwaysOnTop(true);				 
						}
					},
					interval);	
		} else if(awokeBean.isTest()==false){	// 本次提醒已经确认，如果不是test，修改下次提醒时间(注：循环前面已添加)
			
			// 下次时间为本次时间加上间隔
			try {
				String sql="";
				String id = this.getAwokeBean().getId();
				String initTimeStr = this.getAwokeBean().getBeginTime() ;
				String intervalCode = this.getAwokeBean().getInterval() ;
				long intervalNum = this.getAwokeBean().getIntervalNum() ;
				Date td_beginTime = this.getAwokeBean().getThisBeginTime();
				if(intervalCode.equals("0")){		// 不循环					
					sql = "Update "+DirectorConstants.RMD_Awoke+" Set useful='N' Where id="+id;
					// minute,hour,day
				} else {						//循环 
					//td_beginTime.setTime(td_beginTime.getTime() + this.getAwokeBean().getThisInterval() );
					td_beginTime = DirectorStringUtils.getNextBeginTime(initTimeStr, intervalCode, intervalNum) ;
					sql = "Update "+DirectorConstants.RMD_Awoke+" Set NextTime='"+ Formatter.format(td_beginTime,"yyyy-MM-dd HH:mm:ss")+"'" +
							" Where ID="+id+ " AND NextTime< format('"+Formatter.format(td_beginTime,"yyyy-MM-dd HH:mm:ss")+"','yyyy-mm-dd hh:mm:ss')" ;   // 2006-7-26 只将时间改大
				}
				//System.out.println (sql);
				DbBean dbBean = new DbBean(DbBean.DefaultPoolName);
				dbBean.executeUpdate(sql);
					
			}catch(ParseException e){
				e.printStackTrace();
				
			}catch (SQLException e) {
				JOptionPane.showMessageDialog(this,e.getMessage(),"数据库操作失败",JOptionPane.ERROR_MESSAGE);
				e.printStackTrace();
			}
		}
		
		if (this.getCurrentTimerTask()!=null) {
			this.getCurrentTimerTask().cancel();	//停止线程
		}
		this.dispose();	
		
		/// this.dispose();
	}

	/**
	 * This method initializes jButton	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getConfirmButton() {
		if (confirmButton == null) {
			confirmButton = new JButton();
			confirmButton.setBounds(new java.awt.Rectangle(230,149,80,23));
			confirmButton.setText("确 定");
			confirmButton.setEnabled( DirectorContext.isAwokeCloseEnabled() );
			confirmButton.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					log.debug("ok actionPerformed()"); // TODO Auto-generated Event stub actionPerformed()
					closeWindow();
				}
			});
		}
		return confirmButton;
	}

	private JCheckBox timeEnableCheck = null;
	/**
	 * This method initializes time	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JCheckBox getTimeEnableCheckBox() {
		if (timeEnableCheck == null) {
			timeEnableCheck = new JCheckBox();
			timeEnableCheck.setBounds(new java.awt.Rectangle(166,101,18,18));
			timeEnableCheck.setSelected(true);
			timeEnableCheck.addItemListener(this);
		}
		return timeEnableCheck;
	}
	
	/**
	 * This method initializes time	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getTime() {
		if (timeNum == null) {
			timeNum = new JTextField();
			timeNum.setBounds(new java.awt.Rectangle(183,100,25,22));
			timeNum.setEditable(false);
			timeNum.setHorizontalAlignment(JTextField.RIGHT);
			timeNum.setText(currentSeconds+"");
		}
		return timeNum;
	}

	/**
	 * This method initializes jRadioButton_1	
	 * 	
	 * @return javax.swing.JRadioButton	
	 */
	private JLabel getAwokeTimeLabel() {
		if (awokeTimeLabel == null) {
			awokeTimeLabel = new JLabel();
			//System.out.println ("fdsfdsfsdfsd");
			awokeTimeLabel.setBounds(new java.awt.Rectangle(25,160,151,200));
			//jRadioButton_1.addItemListener(this);
			awokeTimeLabel.setText("2006-05-13");
			//awokeTimeLabel.setName("awokeTimeLabelName");
		}
		return awokeTimeLabel;
	}
	
	/**
	 * This method initializes jRadioButton_1	
	 * 	
	 * @return javax.swing.JRadioButton	
	 */
	private JRadioButton getJRadioButton_1() {
		if (jRadioButton_1 == null) {
			jRadioButton_1 = new JRadioButton();
			jRadioButton_1.setBounds(new java.awt.Rectangle(1,122,120,20));
			//jRadioButton_1.addItemListener(this);
			jRadioButton_1.setText("过一会儿再提醒我!");
			jRadioButton_1.setName("rb01");
		}
		return jRadioButton_1;
	}
	/**
	 * This method initializes jRadioButton_2	
	 * 	
	 * @return javax.swing.JRadioButton	
	 */
	private JRadioButton getJRadioButton_2() {
		if (jRadioButton_2 == null) {
			jRadioButton_2 = new JRadioButton();
			jRadioButton_2.setBounds(new java.awt.Rectangle(1,143,80,21));
			//jRadioButton_2.addItemListener(this);
			jRadioButton_2.setName("rb02");
			jRadioButton_2.setText("接受并关闭提醒!");
		}
		return jRadioButton_2;
	}
	/**
	 * This method initializes jComboBox	
	 * 	
	 * @return javax.swing.JComboBox	
	 */
	private JComboBox getJComboBox() {
		if (jComboBox == null) {
			//初始下拉框
			jComboBox = new JComboBox( );
			ComponentUtil.initComboBox(jComboBox, new String[][]{{"1","1 分钟"},
																 {"5","5 分钟"},
																 {"10","10 分钟"},
																 {"30","30 分钟"},
																 {"1", "1 小时"},
																 {"2", "2 小时"},
																 {"5", "5 小时"},
																 {"1", "1 天"} } );
			//System.out.println( jComboBox.getSelectedIndex() ); 
			jComboBox.setSelectedIndex(1); //默认5分钟。
			//System.out.println( jComboBox.getSelectedIndex() ); 
			jComboBox.setBounds(new java.awt.Rectangle(135,121,82,22));
			jComboBox.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

		}
		return jComboBox;
	}

//	/**
//	 * This is the default constructor
//	 */
//	public AwokeMessageDialog() {
//		super();
//		initializeInterface();
//	    //定位到屏幕中央
//	    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
//	    Dimension fs = this.getSize();
//	    if (fs.height > screenSize.height) fs.height = screenSize.height;
//	    if (fs.width > screenSize.width)   fs.width = screenSize.width;
//	    this.setLocation((screenSize.width - fs.width) / 2,
//	                      (screenSize.height - fs.height) / 2);
//
//		//calculagraph
//		calculateTime();
//	}

	/**
	 *
	 */
    public void setVisible(boolean isVisible) {
    	if (Main.isNoDisturbOpen==false) {
    		super.setVisible(isVisible); 
    		//super.show();
        	this.toFront();
    		this.setSize(AwokeMessageDialog.width, AwokeMessageDialog.height);
    		///this.setModal(true);  //remove this
    		this.setAlwaysOnTop(true);
    	}
    }
    
	/**
	 * This is the default constructor
	 */
	public AwokeMessageDialog(AwokeBean p_awokeBean,Timer timer) {
		super();
		//this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)) ;  //ok
		this.setTimer(timer);
		//下面这句要提前。
		this.awokeBean = p_awokeBean;
		fillAwokeBean();
		//this.setIconImage(Toolkit.getDefaultToolkit().createImage(appIco));
		initializeInterface();
//	    //定位到屏幕中央
	    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
	    //Dimension fs = this.getSize();
		/// this.MessageWindowWindowBean.setContent(this.awokeBean.getContent());

		calculateTime( );
	    awokeStyle = this.awokeBean.getAwokeStyle();
	    ///System.out.println("AwokeStyle_MsnTips="+awokeStyle);
		if ( DirectorConstants.AwokeStyle_MsnTips.equals(awokeStyle)) {
			//System.out.println(screenSize.width +"  "+ this.getWidth());
		    this.setLocation((screenSize.width - AwokeMessageDialog.width),
		    		screenSize.height );
		    popupWindow(this);
		}else{
			
			ComponentUtil.setLocationToCenter(this,
					new Dimension(AwokeMessageDialog.width - 2*current_NormalWindow_Num*50,
							AwokeMessageDialog.height - 2*current_NormalWindow_Num*30));
			current_NormalWindow_Num ++;		
		}

		//使用多线程直接打开程序
		if("1".equals(this.awokeBean.getIsOpenFile())){
			final String fileUrl = this.awokeBean.getFileUrl();
			final String openParams = this.awokeBean.getOpenParams();
			try {
				Runnable task = new Runnable() {
		            @Override  
		            public void run() {   
						try {
							System.out.println( "直接打开程序："+fileUrl + " " + fileUrl );
		        			DirectorFileUtils.openFile(fileUrl, openParams);
						} catch (Exception e) {
							log.error(e.getMessage());
						}
		            }   
		        };
		        DirectorContext.getScheduler().schedule(task, 0, TimeUnit.SECONDS);
			} catch (Throwable t) {
				log.error(t);
			}
		}
		
		//使用多线程加载广告，避免网络不可用时窗口要很久才出来
		try {
			Runnable task = new Runnable() {
	            @Override  
	            public void run() {   
					try {
						String url = AdUtil.getAdUrlByType(DirectorConstants.Ad_Block_AwokeMsg);
						getAdLink().setPage(url);
					} catch (Exception e) {
						log.error(e.getMessage());
					}
	            }   
	        };
	        DirectorContext.getScheduler().schedule(task, 5, TimeUnit.SECONDS);
		} catch (Throwable t) {
			log.error(t);
		}
		
	}

	private void fillAwokeBean() {
		Connection conn = null;
		Statement stmt=null;
		ResultSet rs=null;
		try {
			String id = this.awokeBean.getId();
			conn= ApplicationContext.getInstance().getDataSourceManager().getConnection();
			String sql="SELECT SortId, TITLE,TYPE, BEGINTIME, TIMETYPE, INTERVAL,INTERVALNUM, USEFUL, NEEDAFFIRM, CONTENT,AwokeStyle" +
					",Is_Open_File,File_Url,Open_Params FROM "+DirectorConstants.RMD_Awoke+" WHERE ID="+id;
			stmt=conn.createStatement();
			rs=stmt.executeQuery(sql);
			if(rs.next()){ //从数据库查询来填充参数，减少内存使用
				this.awokeBean.setIsOpenFile( rs.getString("Is_Open_File"));
				this.awokeBean.setFileUrl(rs.getString("File_Url"));
				this.awokeBean.setOpenParams( rs.getString("Open_Params"));
				this.awokeBean.setAwokeStyle( rs.getString("AwokeStyle"));
				this.awokeBean.setContent( rs.getString("CONTENT"));
				this.awokeBean.setNeedAffirm( rs.getString("NEEDAFFIRM"));
			}

		} catch (SQLException e1) {
			JOptionPane.showMessageDialog(this,e1.getMessage(),"查询失败",JOptionPane.ERROR_MESSAGE);
			e1.printStackTrace();						
		} finally {
			//释放资源
			wzw.util.DbUtils.closeQuietly(conn, stmt, rs);
		}
	}

	private int currentSeconds=30;
	private void calculateTime(){
	    //timer.  窗口关闭之后，timer自动停止。
		currentTimerTask = new TimerTask() {
		    public void run(){
		    	// getMessageWindowWindowBean().setTime(seconds);
		    	// can't be this.getTime().set...
		    	// System.out.println("----------cal run.");
		    	getTime().setText(String.valueOf(currentSeconds));
			    currentSeconds--;
			    if(currentSeconds<0){		
			    	closeWindow();	 
					/// this.cancel();
			    }
		    }
		};

	    getTimerClock().scheduleAtFixedRate(currentTimerTask,500,1000);     // boom every .5sec starting now
	}

    Timer timerClock = null;
	private Timer getTimerClock() {
		if (timerClock==null) {
			timerClock = new Timer();
		}
		return timerClock;
	}

	private String awokeStyle = null;
	private int current_PopupWindow_Num = 0 ;
	private static List<Integer> Current_PopupWindow_Numbers = new ArrayList<Integer>();
	private static int current_NormalWindow_Num = 0 ;

	private int generateCurrentAvailableNum() {
		int idx = 0;
		for (Integer number : Current_PopupWindow_Numbers) {
			if(number!=idx){  //错动了号码
				Current_PopupWindow_Numbers.add(idx, idx);
				return idx;
			}
			idx++;
		}
		Current_PopupWindow_Numbers.add(Current_PopupWindow_Numbers.size(), idx);
		return idx;
	}
	
	private void popupWindow(AwokeMessageDialog messageWindow){
	    final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		current_PopupWindow_Num = generateCurrentAvailableNum();
		int outHeight = AwokeMessageDialog.height*(current_PopupWindow_Num + 1);
		if (outHeight>screenSize.height) { //如果超出屏幕高度，累积在第一个窗口上方，注意：可以超出工具栏的高度
			outHeight = AwokeMessageDialog.height;
		}
		final int fi_outHeight = outHeight;  //just for final object
//		 Task 1: print "boom", just for test.
		final AwokeMessageDialog mwd = messageWindow;
	    Dimension fs = mwd.getSize() ;
    	int height=mwd.getSize().height;   
    	//System.out.println("11111111111 a");
    	TimerTask moveTask = new TimerTask() {
		    public void run(){
		    	while (true) {
			    	//System.out.println(MessageWindowDialog.height+" "+mwd.getLocation().y);
			    	// 快速移动。。。
		    		if ( screenSize.height-mwd.getLocation().y - DirectorConstants.System_TaskBar_Height < fi_outHeight ) {
				    	mwd.setLocation(mwd.getLocation().x, mwd.getLocation().y-5);
					
				    // 消除误差并跳出
			    	} else if(screenSize.height-mwd.getLocation().y - DirectorConstants.System_TaskBar_Height > fi_outHeight ) {
				    	mwd.setLocation(mwd.getLocation().x, screenSize.height - DirectorConstants.System_TaskBar_Height
				    															- fi_outHeight );
						break;
					
			    	} else {
						break;
					}

					DirectorComponentUtils.sleepQuietly(1);
				}
		    }
	    };	    // Create a timer, and schedule some tasks
 
	    Timer timer = new Timer();
	    timer.schedule(moveTask,10);     // boom every .5sec starting now
    	//System.out.println("2222");
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	/*private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(new BorderLayout());
			jContentPane.add(getMessageWindowWindowBean(), java.awt.BorderLayout.CENTER);
		}
		return jContentPane;
	}*/


	/**
	 * 永远获取焦点, implements WindowListener
	 * @author WZWEN
	 * 
	 */
	  public void windowDeactivated(java.awt.event.WindowEvent e){
		log.debug("Deactivated!!!"); 
	    formWindowDeactivated(e);
	  }		  

		public void windowActivated(java.awt.event.WindowEvent e) {};
		public void windowClosed(java.awt.event.WindowEvent e) {};
		public void windowClosing(java.awt.event.WindowEvent e) {};

		public void windowDeiconified(java.awt.event.WindowEvent e) {};
		public void windowIconified(java.awt.event.WindowEvent e) {};
		public void windowOpened(java.awt.event.WindowEvent e) {};


	private void formWindowDeactivated(java.awt.event.WindowEvent evt)
	{
		log.debug("Deactivated");
		this.toFront();
	}

	public Timer getTimer() {
		return timer;
	}

	public void setTimer(Timer timer) {
		this.timer = timer;
	}

	public AwokeBean getAwokeBean() {
		return awokeBean;
	}

	public void setAwokeBean(AwokeBean awokeBean) {
		this.awokeBean = awokeBean;
	}

	public TimerTask getCurrentTimerTask() {
		if (currentTimerTask==null) {
//			 Task 1: print "boom", just for test.
			currentTimerTask = new TimerTask() {
		    	int seconds=30;
			    public void run(){
			    	/// getMessageWindowWindowBean().setTime(seconds);
			    	// can't be this.getTime().set...
			    	//System.out.println("----------");
			    	getTime().setText(String.valueOf(seconds));
				    seconds--;
				    if(seconds<0){		
				    	closeWindow();	 
						/// this.cancel();
				    }
			    }
		    };	    // Create a timer, and schedule some tasks
		}
		
		return currentTimerTask;
	}

	public void setTimerTask(TimerTask t1) {
		this.currentTimerTask = t1;
	}


	public void update(Observable o, Object arg) {

		ResourceBundle bundle =null;
		bundle = I18nUtils.getBundle(DirectorConstants.I18n_Language_Name);
		
		//this.setTitle( I18nUtil.getBundleString(bundle, MessageWindowDialog.class, "msgWindow.Title"));		//取数据库
		
		int timeInterval = jComboBox.getSelectedIndex() ;	// 不仅仅是更改语言，所以记下当前选择值。
		ComponentUtil.initComboBox(jComboBox,new String[][]{
									{"1m", "1"+I18nUtil.getBundleString(bundle, AwokeMessageDialog.class, "unit.time.minute")},
									{"5m", "5"+I18nUtil.getBundleString(bundle, AwokeMessageDialog.class, "unit.time.minute")},
									{"10m","10"+I18nUtil.getBundleString(bundle, AwokeMessageDialog.class, "unit.time.minute")},
									{"30m","30"+I18nUtil.getBundleString(bundle, AwokeMessageDialog.class, "unit.time.minute")},
									{"1h", "1"+I18nUtil.getBundleString(bundle, AwokeMessageDialog.class, "unit.time.hour")},
									{"2h" ,"2"+I18nUtil.getBundleString(bundle, AwokeMessageDialog.class, "unit.time.hour")},
									{"5h" ,"5"+I18nUtil.getBundleString(bundle, AwokeMessageDialog.class, "unit.time.hour")},
									{"1d" ,"1"+I18nUtil.getBundleString(bundle, AwokeMessageDialog.class, "unit.time.day")},
						});
		jComboBox.setSelectedIndex( timeInterval );//默认10分钟。
		
		jRadioButton_1.setText( I18nUtil.getBundleString(bundle, AwokeMessageDialog.class, "msgWindow.rb_1.Text") );
		jRadioButton_2.setText( I18nUtil.getBundleString(bundle, AwokeMessageDialog.class, "msgWindow.rb_2.Text") );


		jLabel3.setText( I18nUtil.getBundleString(bundle, AwokeMessageDialog.class, "msgWindow.jLabel3.Text") );
		infor_time.setText( I18nUtil.getBundleString(bundle, AwokeMessageDialog.class, "msgWindow.infor_time.Text") );
		//infor.setText( I18nUtil.getBundleString(bundle, MessageWindowDialog.class, "msgWindow.infor.Text") );	//取数据库
		confirmButton.setText( I18nUtil.getBundleString(bundle, AwokeMessageDialog.class, "Button.Ok.Text") );
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		this.lbl_awokeTime.setText( I18nUtil.getBundleString(bundle, AwokeMessageDialog.class, "lbl_awokeTime.Text")+":"+ sdf.format( awokeBean.getThisBeginTime() ));
		this.setTitle( I18nUtil.getBundleString(bundle, AwokeMessageDialog.class, "dialog.Text")+"--"+awokeBean.getTitle() );
	}

	@Override
	public void itemStateChanged(ItemEvent e) {
		Object obj = e.getSource();
		if (obj==getTimeEnableCheckBox()) {
			Boolean enable = getTimeEnableCheckBox().isSelected();
			if (enable) {
				calculateTime();
			}else{
				getCurrentTimerTask().cancel();
			}
		}
	}


}  //  @jve:decl-index=0:visual-constraint="10,10"
